#!/data/data/com.termux/files/usr/bin/python
import getopt
import json
import re
import socket
import sys
from os import path as os_path
import threading
from http.server import CGIHTTPRequestHandler, HTTPServer
from urllib import parse, request

from service.controller import dispatch, init_control
from service.sync_task import save_tem
from service.analysis_task import analysis

enc = "UTF-8"  # 设置返回的编码格式
server = None
socket.setdefaulttimeout(5)

base_home = '/data/data/com.termux/files/home'
cf = {'server': ['0.0.0.0', 8000], 'remote': ['192.168.2.88', 80], 'interval': 30,
      'db': '%s/storage/shared/zpf/zpf.db' % (base_home),
      'check_downtime': 1,
      'check_runaway': 1,
      'check_max_run_time': 0,
      'error_file': '%s/furnace/error.mp3' % (base_home),
      'warn_url': 'http://localhost:8000/cgi-bin/warn.py'}


def write_cf(ccf):
    with open('furnace.conf', 'w') as wcf:
        wcf.write(json.dumps(ccf, indent=4))


try:
    with open('furnace.conf', 'r') as rcf:
        constr = rcf.read().strip()
        if constr:
            cf = json.loads(constr)
except:
    write_cf(cf)

init_control(cf)


def start_task(task, args):
    th = threading.Thread(target=task, args=(args,))
    th.setDaemon(True)  # 守护线程
    th.start()


class MyRequestHandler(CGIHTTPRequestHandler):

    def do_GET(self):
        query = parse.urlparse(self.path)
        if query.path == '/' or re.search(r'/remote', query.path):
            res = ''
            req_line = 'GET %s HTTP/1.1' % re.sub(r'.+?remote', '', self.path)
            try:
                s = socket.socket()
                s.connect(tuple(cf['remote']))
                s.send(req_line.encode())
                res = s.recv(5120).decode('gbk')
            except Exception as error:
                print(error)
            finally:
                s.close()
            is_warn = os_path.exists(cf['error_file'])
            if not res:
                with open('www/temp.html', 'r', encoding='UTF-8') as rcf:
                    res = rcf.read().strip()
            last = re.sub(r'src=.+?loadhead.js">', 'src="/www/loadhead.js">', res)
            last = re.sub(r'stopT', 'isWarn:%d,stopT' % is_warn, last)
            last = re.sub(r'(window.+?)/', r'\1/remote/', last)
            if not last:
                last = '<h1>获取远程%s地址数据失败</h1>' % (cf['remote'])
            self.do_action(last, 'text/html;charset=%s' % enc)
            return
        elif re.match(r'/api', query.path):
            res = dispatch(query.path, parse.parse_qs(query.query))
            self.do_action(res)
            return
        CGIHTTPRequestHandler.do_GET(self)

    def do_POST(self):
        path = str(self.path)  # 获取请求的url
        length = int(self.headers["Content-length"])
        request_str = self.rfile.read(length).decode(enc)
        query_body = json.loads(request_str)
        if re.match(r'/api', path):
            res = dispatch(path, query_body)
            self.do_action(res)
            return
        CGIHTTPRequestHandler.do_POST(self)

    def do_action(self, content, content_type="application/json;charset=%s" % enc):
        print(content)
        self.send_response(200)  # 返回状态码
        self.send_header("Content-type", content_type)  # 返回响应头内容
        self.end_headers()  # 返回响应头结束
        if re.search(r'json', content_type):
            content = json.dumps(content)
        self.wfile.write(content.encode(enc))  # 发送json格式的返回包体


def start_server(conf):
    hp = tuple(conf)
    global server
    server = HTTPServer(hp, MyRequestHandler)
    print("Starting CGIServer, listen at: %s:%s" % hp)
    server.serve_forever()


def main(argv):
    helps = 'http_server.furnace -a <addr> -p <port> -t <interval>'
    try:
        opts, args = getopt.getopt(argv, "hla:p:t", ["addr=", "port=", "interval=", "log"])
    except getopt.GetoptError:
        print(helps)
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(helps)
            sys.exit()
        elif opt in ("-a", "--addr"):
            cf['remote'][0] = arg
        elif opt in ("-l", "--log"):
            sys.stderr = open('error.log', 'a')
            sys.stdout = open('out.log', 'a')
        elif opt in ("-p", "--port"):
            cf['remote'][1] = arg
        elif opt in ("-t", "--interval"):
            cf['interval'] = arg

    print(cf)
    start_task(save_tem, cf)
    start_task(analysis, cf)
    start_server(cf['server'])


if __name__ == "__main__":
    main(sys.argv[1:])
